package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.api.API;
import com.example.domain.Girls;
import com.example.recyclerview.RecyclerViewAdapter;
import com.example.recyclerview.SimpleRecyclerViewAdapter;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/23.
 */
public class ContentFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private List<Girls.ResultsBean> girls = new ArrayList<>();
    private int page = 0;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean mIsFirstTouchedBttom = true;
    private int tag;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Fresco.initialize(getActivity());
        View view = inflater.inflate(R.layout.fragment_layout,null);

        recyclerView = (RecyclerView) view.findViewById(R.id.fragment_recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);


        swipeRefreshLayout.measure(View.MEASURED_SIZE_MASK, View.MEASURED_HEIGHT_STATE_SHIFT);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright);

        if(tag==R.id.nav_girls){
            initRecyclerView();
        } else {
            initSimpleRecyclerView();
        }

        onRefresh();
        swipeRefreshLayout.setOnRefreshListener(this);
        return view;
    }
    public void setValue(Integer i){
        this.tag = i;
    }

    private void initRecyclerView() {
        final StaggeredGridLayoutManager staggeredGridLayoutManager =
                new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        final RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), girls);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int[] lastVisiblePositions = new int[2];
                //找到最后可见item的位置
                lastVisiblePositions = staggeredGridLayoutManager
                        .findLastCompletelyVisibleItemPositions(lastVisiblePositions);
                int right = lastVisiblePositions[1];
                boolean isBttom = right > adapter.getItemCount() - 7;
                if (isBttom && !swipeRefreshLayout.isRefreshing()) {
                    if (!mIsFirstTouchedBttom) {
                        onRefresh();
                    } else mIsFirstTouchedBttom = false;
                }
            }
        });
        adapter.setRecyclerViewOnItemClickLitener(new RecyclerViewAdapter.RecyclerViewOnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(),FullscreenActivity.class);
                intent.putExtra("Girls", (Serializable) girls);
                intent.putExtra("position",String.valueOf(position));
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }
    private void initSimpleRecyclerView() {
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        final SimpleRecyclerViewAdapter adapter = new SimpleRecyclerViewAdapter(getActivity(),girls);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //找到最后可见item的位置
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                boolean isBttom = lastVisibleItemPosition > adapter.getItemCount() - 7;
                if (isBttom && !swipeRefreshLayout.isRefreshing()) {
                    if (!mIsFirstTouchedBttom) {
                        onRefresh();
                    } else mIsFirstTouchedBttom = false;
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        page++;
        swipeRefreshLayout.setRefreshing(true);
        getGirls(page);
    }

    private void getGirls(int page) {

        API api = com.example.net.Retrofit.getRetrofit().create(API.class);
        Call<Girls> girls = getCall(page, api);
        enqueue(girls);
    }

    private Call<Girls> getCall(int page, API api) {
        switch (tag){
            case R.id.nav_ganhuo:
                return api.getGanhuo(page);
            case R.id.nav_slideshow:
                return api.getVido(page);
            case R.id.nav_girls:
                return api.getGirls(page);
            case R.id.nav_manage:
                return api.getExpandingResources(page);
            case R.id.nav_web:
                return api.getWeb(page);
        }
        return null;
    }

    private void enqueue(Call<Girls> girls) {
        girls.enqueue(new Callback<Girls>() {
            @Override
            public void onResponse(Call<Girls> call, Response<Girls> response) {
                Girls body = response.body();
                List<Girls.ResultsBean> results = body.getResults();
                if(results.size()==0){
                    showSnackbar();
                }
                loadMore(results);
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<Girls> call, Throwable t) {
                //加载失败
                showSnackbar();
            }
        });
    }

    private void loadMore(List<Girls.ResultsBean> results) {
        for (Girls.ResultsBean girl : results) {
            girls.add(girl);
        }
        recyclerView.requestLayout();
    }

    private void showSnackbar() {
        Snackbar.make(recyclerView, "加载失败，请重试", Snackbar.LENGTH_LONG)
                .setAction("重试", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onRefresh();
                    }
                })
                .show();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.clearMemoryCaches();
        imagePipeline.clearDiskCaches();

        // combines above two lines
        imagePipeline.clearCaches();
    }
}
